package com.lg.curator;

import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryNTimes;

public class DistributionLock {

	private static final ThreadLocal<CuratorFramework> CuratorTHREADLOCAL = new ThreadLocal<>();
	private static final ThreadLocal<String> PathTHREADLOCAL = new ThreadLocal<>();
	static String CONNECTSTRING = "127.0.0.1:2181";
	static String LOCKPATH = "/lock";
	static CuratorFramework client ;
	public static void main(String[] args) {
		
		 client = CuratorFrameworkFactory.newClient(CONNECTSTRING, new RetryNTimes(10, 5000));
		client.start();
		CuratorTHREADLOCAL.set(client);
		PathTHREADLOCAL.set(LOCKPATH);
		 Thread t1 = new Thread(() -> {
	            doWithLock();
	        }, "t1");
	        Thread t2 = new Thread(() -> {
	            doWithLock();
	        }, "t2");

	        t1.start();
	        t2.start();
	}
	
	public static void doWithLock() {
		InterProcessMutex lock = new InterProcessMutex(client, LOCKPATH );
		try {
			if(lock.acquire(10 * 1000, TimeUnit.SECONDS)) {
				   System.out.println(Thread.currentThread().getName() + " hold lock");
	                Thread.sleep(5000L);
	                System.out.println(Thread.currentThread().getName() + " release lock");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				lock.release();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}
